/* eslint-disable @typescript-eslint/ban-types */
/* eslint-disable no-nested-ternary */
/*
 * @Author: your name
 * @Date: 2021-05-07 16:47:38
 * @LastEditTime: 2021-06-11 17:45:38
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \umi\src\pages\renewalDetail\index.tsx
 */
import ProductListTableForModal from '@/components/ProductListTableForModal';
import type { ConnectState } from '@/models/connect';
import PENCIL from '@/pages/renewalEdite/images/pencil.svg';
import type { ICommonResponse } from '@/services/renewal';
import { SearchOutlined } from '@ant-design/icons';
import type { RadioChangeEvent } from 'antd';
import { Button, Checkbox, Input, message, Modal, Popconfirm, Radio, Select, Table } from 'antd';
import classNames from 'classnames';
import React, { Component } from 'react';
import type { ConnectProps } from 'umi';
import { connect, history } from 'umi';
import _ from 'underscore';
import { FeatureTypes, ProductStatus } from '../renewalDetail/data.d';
import type {
  operationSearchParam,
  proProductListCloumns, smsColumns
} from '../renewalPanel/data.d';
import type { IMatch, IProductDetail, IProductVo, ISmsTempList } from './data.d';
import styles from './index.less';

const PRODUCT_STATUS_MAP: Record<ProductStatus, string> = {
  [ProductStatus.All]: '全部',
  [ProductStatus.WAIT]: '待审',
  [ProductStatus.SALES]: '上架',
  [ProductStatus.UNSALES]: '下架',
  [ProductStatus.TEST]: '测试',
  [ProductStatus.STOP]: '停售',
};
const FEATURE_TYPES_MAP: Record<string, FeatureTypes> = {
  renewal: FeatureTypes.renewalProductVoList,
  origin: FeatureTypes.originalProductVo,
  replace: FeatureTypes.replaceProductVo,
};
export type RenewalPanelProps = {
  match: IMatch;
  productDetail: IProductDetail;
  totalModalR: number;
  pageIndexModalR: number;
  productModalListR: proProductListCloumns[];
  smsTemplates: ISmsTempList[];
} & Partial<ConnectProps>;

type IState = {
  visibleProductModal: boolean;
  visibleSmsModal: boolean;
  productIdModal: string | number;
  productNameModal: string | number;
  smsSelect: smsColumns;
  smsTypeInModal: number;
  pointTypeInModal: number;
  daysInModal: string | number;
  searchOperation: operationSearchParam;
};

class RenewalEditePanel extends Component<RenewalPanelProps, IState> {
  props: any;
  constructor(props: RenewalPanelProps) {
    super(props);
    this.state = {
      visibleProductModal: false,
      visibleSmsModal: false,
      productIdModal: '',
      productNameModal: '',
      smsSelect: {
        createTime: '',
        id: 0,
        isInit: false,
        pointType: 0,
        pointValue: '',
        productId: 0,
        smsType: 0,
        templateContent: '',
        templateKey: '',
        updateTime: '',
      },
      smsTypeInModal: 0,
      pointTypeInModal: 0,
      daysInModal: '',
      searchOperation: {},
    };
  }
  componentDidMount() {
    // eslint-disable-next-line no-console
    console.log('ComponentDidMount', this.props.match.params);
    // 网络请求
    const { dispatch } = this.props;
    const { id = '' } = this.props.match.params;
    if (id || id === '0') {
      if (dispatch) {
        dispatch({
          type: 'renewal/getRenewalProductDetail',
          payload: { id },
        });
        this.renderSelectSmsTempData();
      }
    }
  }
  // 切换radio
  switchRadio = (e: RadioChangeEvent) => {
    const { dispatch } = this.props;
    if (dispatch) {
      dispatch({
        type: 'renewal/fakeUpdateProductDetail',
        payload: {
          featuredProductId: e.target.value.split('-')[1],
          featuredType: e.target.value.split('-')[0],
        },
        // eslint-disable-next-line no-console
      });
    }
  };
  // 确定保存修改
  upConfigSure = () => {
    const { productDetail, dispatch } = this.props;
    const { id = '' } = this.props.match.params;
    if (!productDetail.featuredProductId) {
      message.info('未设置推荐产品');
      return;
    }
    if (dispatch) {
      dispatch({
        type: 'renewal/updateConfig',
        payload: {
          featuredProductId: productDetail.featuredProductId,
          featuredType: productDetail.featuredType,
          id: productDetail.id,
          open: productDetail.isSmsTip,
          replaceProductId: productDetail.replaceProductVo
            ? productDetail.replaceProductVo.operProductId
            : '',
        },
        // eslint-disable-next-line no-console
      }).then((jsons: ICommonResponse<null>) => {
        if (jsons.success) {
          message.success('保存成功');
          dispatch({
            type: 'renewal/getRenewalProductDetail',
            payload: { id },
          });
        }
      });
    }
  };
  // 放弃修改
  upConfigNo = () => {
    return history.push(`/product-management/renewal-list`);
    // const { dispatch } = this.props;
    // const { id = '' } = this.props.match.params;
    // if (dispatch) {
    //   dispatch({
    //     type: 'renewal/getRenewalProductDetail',
    //     payload: { id },
    //   });
    // }
  };
  // 打开产品Modal
  openModalProduct = () => {
    const { dispatch } = this.props;
    const { searchOperation } = this.state;
    if (dispatch) {
      dispatch({
        type: 'renewal/getRenewalProductForModalR',
        payload: {
          ...searchOperation,
          pageSize: 7,
          pageIndex: 1,
        },
        // eslint-disable-next-line no-console
      }).then((jsons: ICommonResponse<proProductListCloumns[]>) => {
        // eslint-disable-next-line no-console
        console.log('........', jsons);
        if (jsons.success) {
          this.setState({
            visibleProductModal: true,
          });
        }
      });
    }
  };
  // 关闭产品Modal
  closeModalProduct = () => {
    this.setState({
      visibleProductModal: false,
      searchOperation: {},
      productIdModal: '',
      productNameModal: '',
    });
  };
  // 勾勾是否发送
  onChangeSend = (e: { target: { checked: boolean } }) => {
    const { dispatch } = this.props;
    if (dispatch) {
      dispatch({
        type: 'renewal/fakeUpdateProductDetail',
        payload: {
          isSmsTip: e.target.checked,
        },
        // eslint-disable-next-line no-console
      });
    }
  };
  // 我翻阅下个季节
  onPageChange = (pageNum: number) => {
    console.log('页码', pageNum);
    const { dispatch } = this.props;
    const { searchOperation } = this.state;
    if (dispatch) {
      dispatch({
        type: 'renewal/getRenewalProductForModalR',
        payload: {
          ...searchOperation,
          pageSize: 7,
          pageIndex: pageNum,
        },
      });
    }
  };
  // 点击去掉替代产品
  deleteReplace = () => {
    const { dispatch } = this.props;
    if (dispatch) {
      dispatch({
        type: 'renewal/fakeUpdateProductDetail',
        payload: {
          replaceProductVo: {
            operProductId: '',
            productName: '',
            productStatus: '',
          },
        },
        // eslint-disable-next-line no-console
      });
    }
  };
  // 点击添加或取消
  handleProduct = (productItem: proProductListCloumns) => {
    console.log('产品', productItem);
    // updateReplace
    const { dispatch } = this.props;
    if (dispatch) {
      dispatch({
        type: 'renewal/fakeUpdateProductDetail',
        payload: {
          replaceProductVo: {
            operProductId: productItem.productId,
            productName: productItem.productName,
            productStatus: productItem.productStatus || 1,
          },
          featuredProductId: '',
        },
        // eslint-disable-next-line no-console
      }).then((jsons: { success: boolean }) => {
        if (jsons.success) {
          this.setState({
            visibleProductModal: false,
            searchOperation: {},
            productIdModal: '',
            productNameModal: '',
          });
        }
      });
    }
  };
  handleSearchInModal = () => {
    const { productIdModal, productNameModal } = this.state;
    const { dispatch } = this.props;
    this.setState(
      {
        searchOperation: {
          productId: productIdModal,
          productName: productNameModal,
        },
      },
      () => {
        if (dispatch) {
          const { searchOperation } = this.state;
          dispatch({
            type: 'renewal/getRenewalProductForModalR',
            payload: {
              ...searchOperation,
              pageSize: 7,
              pageIndex: 1,
            },
            // eslint-disable-next-line no-console
          }).then((jsons: ICommonResponse<proProductListCloumns[]>) => {
            // eslint-disable-next-line no-console
            console.log('........', jsons);
            if (jsons.success) {
              this.setState({
                visibleProductModal: true,
              });
            }
          });
        }
      },
    );
  };

  // 点击编辑短信模板,打开
  handleSms = (smsItem: smsColumns) => {
    console.log(smsItem);
    this.setState({
      visibleSmsModal: true,
      smsSelect: smsItem,
      smsTypeInModal: smsItem.smsType,
      pointTypeInModal: smsItem.pointType,
      daysInModal: smsItem.pointValue,
    });
  };
  // 关闭短信Modal
  closeModalSms = () => {
    this.setState({
      visibleSmsModal: false,
    });
  };
  // 点击短信Modal‘确定’
  handleOk = () => {
    // some code
    const { dispatch, productDetail } = this.props;
    const { smsTypeInModal, pointTypeInModal, smsSelect, daysInModal } = this.state;
    if (dispatch) {
      dispatch({
        type: 'renewal/updateSms',
        payload: {
          productId: productDetail.operProductId,
          pointType: pointTypeInModal,
          smsType: smsTypeInModal,
          pointValue: daysInModal,
          id: smsSelect.id,
        },
        // eslint-disable-next-line no-console
      }).then((jsons: ICommonResponse<smsColumns[]>) => {
        if (jsons.success) {
          // 暂时改变productDetail里面的值
          dispatch({
            type: 'renewal/fakeUpdateProductDetail',
            payload: {
              smsTemplateVos: jsons.data,
            },
          });
          message.success('修改成功');
        }
      });
    }
    this.setState({
      visibleSmsModal: false,
    });
  };
  confirmSms = () => {
    const { dispatch, productDetail } = this.props;
    if (dispatch) {
      dispatch({
        type: 'renewal/getResetSms',
        payload: { productId: productDetail.operProductId },
        // eslint-disable-next-line no-console
      }).then((jsons: ICommonResponse<smsColumns>) => {
        // 暂时改变productDetail里面的值
        if (jsons.success) {
          dispatch({
            type: 'renewal/fakeUpdateProductDetail',
            payload: {
              smsTemplateVos: jsons.data,
            },
            // eslint-disable-next-line no-console
          });
          message.success('重置成功');
        }
      });
    }
  };
  changeModalSmsType = (e: number) => {
    this.setState({
      smsTypeInModal: e,
    });
  };
  changePointType = (e: number) => {
    this.setState({
      pointTypeInModal: e,
    });
  };
  renderPlans = (plans: any): string => {
    // 上面这个参数没法定义
    const valusArray = _.values(plans);
    if (valusArray.length) {
      return valusArray.join('/');
    }
    return '--';
  };
  // eslint-disable-next-line consistent-return
  renderSelectSmsTempData = () => {
    const { dispatch } = this.props;
    if (dispatch) {
      dispatch({
        type: 'renewal/smsTemplates',
        payload: {},
        // eslint-disable-next-line no-console
      });
    }
  };
  renderModalSmsContent = () => {
    const { smsTypeInModal } = this.state;
    const { smsTemplates } = this.props;
    const fit = smsTemplates.filter((o: ISmsTempList) => o.smsType === smsTypeInModal)[0];
    if (fit) {
      return fit.content;
    }
    return '';
  };
  renderSelectSmsTemp = () => {
    const { smsTemplates } = this.props;
    const dataDoms = smsTemplates.map((iyu: ISmsTempList) => {
      return <Select.Option value={iyu.smsType}>{iyu.key}</Select.Option>;
    });
    return dataDoms;
  };
  render() {
    const { productDetail, totalModalR, pageIndexModalR, productModalListR } = this.props;
    const { visibleProductModal, visibleSmsModal, productNameModal, productIdModal } = this.state;
    const columns = [
      {
        title: '通知时间',

        width: 184,
        render: (record: smsColumns) => {
          return `保险到期日${record.pointType === 1 ? '提前' : '延后'}${record.pointValue}天`;
        },
      },
      {
        title: '通知内容',
        dataIndex: 'templateContent',
        key: 'templateContent',
      },
      {
        title: '操作',
        width: 172,
        render: (record: smsColumns) => {
          return (
            <div
              onClick={() => {
                this.handleSms(record);
              }}
              className={styles.toolsLites}
            >
              编辑
            </div>
          );
        },
      },
    ];
    return (
      <div className={styles.renewalDetailWarp}>
        {/* 顶部商品展示 */}
        <div className={styles.topShows}>
          <div className={styles.bread}>
            <span
              onClick={() => {
                history.push(`/product-management/renewal-list`);
              }}
            >
              续保商品管理
            </span>{' '}
            <span>/</span> <span>{productDetail.productName}</span>
          </div>
          <div className={styles.productName}>{productDetail.productName}</div>
          {/* 小块块展示 */}
          <div className={styles.productInfosWarp}>
            <div className={styles.clo}>
              <div className={styles.item}>
                <div>运营产品ID:</div>
                <div>{productDetail.operProductId}</div>
              </div>

              <div className={styles.item}>
                <div>计划名称:</div>
                <div>{this.renderPlans(productDetail.plans)}</div>
              </div>
            </div>

            <div className={styles.clo}>
              <div className={styles.item}>
                <div>产品类别:</div>
                <div>{productDetail.categoryMasterName}</div>
              </div>

              <div className={styles.item}>
                <div>产品状态:</div>
                <div>{PRODUCT_STATUS_MAP[productDetail.productStatus]}</div>
              </div>
            </div>

            <div className={styles.clo}>
              <div className={styles.item}>
                <div>基础产品ID:</div>
                <div>{productDetail.baseProductId}</div>
              </div>

              <div className={styles.item}>
                <div>基础产品名称:</div>
                <div>{productDetail.baseProductName}</div>
              </div>
            </div>
          </div>
        </div>

        <div className={styles.scrollWarp}>
          {/* 第二回合 续保规则设置 */}
          <div className={classNames(styles.renewalRuleWarp, styles.infoWarp)}>
            <div className={styles.balckTitle}>续保规则设置</div>
            {/* 主要信息展示 */}
            <div className={styles.infoContent}>
              <div className={styles.col}>
                <div>短险续保规则：</div>
                <div>
                  {productDetail.renewalWay || productDetail.renewalWay === 0
                    ? productDetail.renewalWay === 0
                      ? '不支持续保'
                      : productDetail.renewalWay === 1
                      ? '保司续保'
                      : '慧择续保'
                    : '--'}
                </div>
              </div>

              <div className={styles.col}>
                <div>最早可提前续保日：</div>
                <div>
                  {productDetail.renewalStartDay || productDetail.renewalStartDay === 0
                    ? `${productDetail.renewalStartDay}天`
                    : '--'}
                </div>
              </div>

              <div className={styles.col}>
                <div>最晚可提前续保日：</div>
                <div>
                  {productDetail?.renewalGracePeriod || productDetail?.renewalGracePeriod === 0
                    ? `${productDetail.renewalGracePeriod}天`
                    : '--'}
                </div>
              </div>
              <Radio.Group
                value={`${productDetail.featuredType}-${productDetail.featuredProductId}`}
                onChange={this.switchRadio}
              >
                {productDetail.renewalProductVoList ? (
                  <div className={styles.col}>
                    <div>续保产品：</div>
                    <div className={styles.choise}>
                      {productDetail.renewalProductVoList.map((ite: IProductVo) => {
                        return (
                          <div
                            className={classNames(styles.productChoise, styles.productChoiseMany)}
                          >
                            <div>{`${ite.productName}(${
                              PRODUCT_STATUS_MAP[ite.productStatus] || '--'
                            })`}</div>
                            <Radio value={`${FEATURE_TYPES_MAP.renewal}-${ite.operProductId}`}>
                              推荐
                            </Radio>
                          </div>
                        );
                      })}
                    </div>
                  </div>
                ) : null}

                {productDetail.originalProductVo ? (
                  <div className={styles.col}>
                    <div>原产品：</div>
                    <div className={styles.productChoise}>
                      <div>{`${productDetail.originalProductVo.productName}(${
                        PRODUCT_STATUS_MAP[productDetail.originalProductVo.productStatus] || '--'
                      })`}</div>
                      <Radio
                        value={`${FEATURE_TYPES_MAP.origin}-${productDetail.originalProductVo.operProductId}`}
                      >
                        推荐
                      </Radio>
                    </div>
                  </div>
                ) : null}

                {productDetail.replaceProductVo && productDetail.replaceProductVo.operProductId ? (
                  <div className={styles.col}>
                    <div>替代产品：</div>
                    <div className={styles.productChoise}>
                      <div>
                        <span>{`${productDetail.replaceProductVo.productName}(${
                          PRODUCT_STATUS_MAP[productDetail.replaceProductVo.productStatus] || '--'
                        })`}</span>
                        <img
                          onClick={this.openModalProduct}
                          src={PENCIL}
                          className={styles.pencil}
                        />
                        {/* <img onClick={this.deleteReplace} src={LAJI} className={styles.pencil} /> */}
                      </div>
                      <Radio
                        value={`${FEATURE_TYPES_MAP.replace}-${productDetail.replaceProductVo.operProductId}`}
                      >
                        推荐
                      </Radio>
                    </div>
                  </div>
                ) : (
                  <div className={styles.col}>
                    <div>替代产品：</div>
                    <div className={styles.productChoise}>
                      <div>未设置替代产品</div>
                      <Button type="primary" size="small" onClick={this.openModalProduct}>
                        设置替代产品
                      </Button>
                    </div>
                  </div>
                )}
              </Radio.Group>
            </div>
          </div>

          {/* 第三回合 续保规则设置 */}
          {productDetail.smsTemplateVos && (
            <div
              className={classNames(styles.renewalRuleWarp, styles.infoWarp)}
              style={{ marginBottom: 80 }}
            >
              <div className={styles.balckTitle}>续保通知规则</div>
              {/* 主要信息展示 */}
              <div className={styles.infoContent}>
                <div className={styles.tableWarps}>
                  <div className={styles.gougouTips}>
                    <Checkbox checked={productDetail.isSmsTip} onChange={this.onChangeSend}>
                      是否通知续保
                    </Checkbox>
                    <Popconfirm title="确认重置续保通知规则" onConfirm={this.confirmSms}>
                      <Button type="primary">重置</Button>
                    </Popconfirm>
                  </div>
                  <Table
                    columns={columns}
                    bordered
                    pagination={false}
                    dataSource={productDetail.smsTemplateVos}
                  />
                </div>
              </div>
            </div>
          )}
        </div>

        {/* 第四回合 沉底按钮 */}
        <div className={styles.fixBotButs}>
          <Button ghost type="primary" onClick={this.upConfigNo} style={{ marginRight: 16 }}>
            取消
          </Button>
          <Button type="primary" onClick={this.upConfigSure}>
            保存
          </Button>
        </div>

        {/* 添加商品弹框 */}
        <Modal
          closable={true}
          footer={null}
          maskClosable={false}
          title="设置替代产品"
          width={900}
          visible={visibleProductModal}
          onCancel={this.closeModalProduct}
          centered={true}
        >
          <div className={styles.searchTools}>
            <Input
              style={{ width: 167, marginRight: 16 }}
              placeholder="请输入商品ID"
              type="number"
              suffix={<SearchOutlined />}
              value={productIdModal}
              onChange={(e) => {
                this.setState({ productIdModal: e.target.value });
              }}
            />

            <Input
              style={{ width: 167, marginRight: 16 }}
              placeholder="请输入商品名称"
              suffix={<SearchOutlined />}
              value={productNameModal}
              onChange={(e) => {
                this.setState({ productNameModal: e.target.value });
              }}
            />

            <Button type="primary" onClick={this.handleSearchInModal}>
              查询
            </Button>
          </div>

          <ProductListTableForModal
            dataSource={productModalListR}
            pageSize={7}
            type="replace"
            handleProduct={this.handleProduct}
            onPageChange={this.onPageChange}
            total={totalModalR}
            pageIndex={pageIndexModalR}
          />
        </Modal>

        {/* 续保通知规则弹窗 */}
        <Modal
          closable={true}
          maskClosable={false}
          title="短信发送规则"
          width={900}
          visible={visibleSmsModal}
          onCancel={this.closeModalSms}
          onOk={this.handleOk}
          centered={true}
        >
          <div className={styles.smsMainWarps}>
            <div className={styles.cols}>
              <div className={styles.labelName}>设置提醒时间：</div>
              <div className={styles.rightContent}>
                <div style={{ marginRight: 8 }}>在保单到期时</div>
                <div>
                  <Select
                    value={this.state.pointTypeInModal}
                    style={{ width: 89, marginRight: 8 }}
                    onChange={this.changePointType}
                  >
                    <Select.Option value={1}>提前</Select.Option>
                    <Select.Option value={2}>延后</Select.Option>
                  </Select>
                </div>
                <Input
                  value={this.state.daysInModal}
                  onChange={(e) => {
                    this.setState({ daysInModal: e.target.value });
                  }}
                  style={{ width: 98, marginRight: 8 }}
                  placeholder="请输入"
                />
                <div>天，进行续保提醒</div>
              </div>
            </div>

            <div className={styles.cols}>
              <div className={styles.labelName}>短信模板：</div>
              <div className={styles.rightContent}>
                <div>
                  <Select
                    onChange={this.changeModalSmsType}
                    defaultValue={this.state.smsTypeInModal}
                    style={{ width: 216 }}
                  >
                    {this.renderSelectSmsTemp()}
                  </Select>
                </div>
              </div>
            </div>

            <div className={styles.cols} style={{ alignItems: 'flex-start' }}>
              <div className={styles.labelName}>短信模板：</div>
              <div className={styles.rightContent}>
                <div>
                  <Input.TextArea
                    value={this.renderModalSmsContent()}
                    readOnly={true}
                    bordered={true}
                    style={{ width: 513, height: 128 }}
                  />
                </div>
              </div>
            </div>
          </div>
        </Modal>
      </div>
    );
  }
}

export default connect(({ renewal }: ConnectState) => ({
  productDetail: renewal.productDetail,
  totalModalR: renewal.totalModalR,
  pageIndexModalR: renewal.pageIndexModalR,
  productModalListR: renewal.productModalListR,
  smsTemplates: renewal.smsTemplates,
}))(RenewalEditePanel);
